/*
 * @Description:
 * @version:
 * @Author: sunqian_sr
 * @Date: 2023-01-12 11:30:43
 * @LastEditors: Andy
 * @LastEditTime: 2023-03-29 15:29:47
 */
import { cloneDeep } from '@package/utils'
import { defineStore } from '@/common/config/defineStore'

export default defineStore('cachedView', {
  state: () => ({
    visitedViews: [{ path: '/home', title: '首页' }],
    cachedViews: ['首页'],
    reload: '', // 代表刷新当前页面，name参数
    isReload: '' // 标识刷新当页事件
  }),
  // 相当于 vue 中的 computed 计算属性 返回一个数值
  getters: {},
  actions: {
    reloadView(name) {
      this.reload = name
      this.isReload = new Date().getTime()
    },
    clearViews() {
      this.visitedViews = []
      this.cachedViews = []
      console.log('visitedViews: ', this.visitedViews, this.cachedViews)
    },
    addView(view) {
      const routerView = {
        title: view.meta?.title ?? 'no-name',
        path: view.path,
        query: view.query,
        name: view.name,
        meta: view.meta
      }
      const result = JSON.parse(sessionStorage.getItem('visitedViews'))
      if (!this.visitedViews.length && result) {
        this.visitedViews = result
      }
      this.addVisitedView(routerView)
      this.addCachedView(routerView)
    },
    addVisitedView(view) {
      if (this.visitedViews.some((v) => v.path === view.path)) return
      this.visitedViews.push(view)
      sessionStorage.setItem('visitedViews', JSON.stringify(this.visitedViews))
    },
    addCachedView(view) {
      if (this.cachedViews.includes(view.name)) return
      if (view.meta && view.meta.keepAlive) {
        this.cachedViews.push(view.name)
      }
    },
    delVisitedView(path) {
      for (const [i, v] of this.visitedViews.entries()) {
        if (v.path === path && v.path !== '/home') {
          this.visitedViews.splice(i, 1)
          break
        }
      }
      sessionStorage.setItem('visitedViews', JSON.stringify(this.visitedViews))
    },
    delOtherVisitedViews(arr) {
      this.visitedViews = this.visitedViews.filter((v) => {
        // home页面作为初始页面，不允许删除
        return !arr.includes(v.path) || v.path === '/home'
      })
      sessionStorage.setItem('visitedViews', JSON.stringify(this.visitedViews))
      console.log('delOtherVisitedViews ', this.visitedViews)
    },
    delCachedView(view) {
      const index = this.cachedViews.indexOf(view.name)
      index > -1 && this.cachedViews.splice(index, 1)
      console.log('this.cachedViews: ', this.cachedViews)
    },
    delOtherCachedView(arr) {
      console.log('arr: ', arr)
      this.cachedViews = this.cachedViews.filter((v) => {
        // home页面作为初始页面，不允许删除
        return !arr.includes(v)
      })
      console.log(this.cachedViews, '----delOtherCachedView-----')
    }
  }
})
